package com.ruoyi.training.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.training.CurriculumConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.training.domain.*;
import com.ruoyi.training.mapper.*;
import com.ruoyi.training.service.ITrainPlanExamService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 培训计划抽卷Service业务层处理
 *
 * @author wng
 * @date 2024-08-04
 */
@Service
public class TrainPlanExamServiceImpl implements ITrainPlanExamService {
    @Resource
    private TrainPlanExamMapper trainPlanExamMapper;
    @Resource
    private TrainPlanPaperMapper trainPlanPaperMapper;
    @Resource
    private TrainPlanPaperQuestionMapper trainPlanPaperQuestionMapper;
    @Resource
    private ExamQuestionMapper examQuestionMapper;
    @Resource
    private ExamQuestionOptionMapper examQuestionOptionMapper;
    @Resource
    private CurriculumMapper curriculumMapper;
    @Resource
    private CurriculumChapterMapper curriculumChapterMapper;

    /**
     * 查询培训计划抽卷
     *
     * @param id 培训计划抽卷主键
     * @return 培训计划抽卷
     */
    @Override
    public TrainPlanExam selectTrainPlanExamById(Long id) {
        return trainPlanExamMapper.selectTrainPlanExamById(id);
    }

    /**
     * 查询培训计划抽卷列表
     *
     * @param trainPlanExam 培训计划抽卷
     * @return 培训计划抽卷
     */
    @Override
    public List<TrainPlanExam> selectTrainPlanExamList(TrainPlanExam trainPlanExam) {
        return trainPlanExamMapper.selectTrainPlanExamList(trainPlanExam);
    }

    /**
     * 新增培训计划抽卷
     *
     * @param trainPlanExam 培训计划抽卷
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTrainPlanExam(TrainPlanExam trainPlanExam) {
//        trainPlanExam.setCreateTime(DateUtils.getNowDate());
        //新增planExam记录
        List<TrainPlanExam> planExams = JSON.parseArray(JSON.toJSONString(trainPlanExam.getParams().get("planExams")), TrainPlanExam.class);
        Date nowDate = DateUtils.getNowDate();

        TrainPlanPaper paper = new TrainPlanPaper(trainPlanExam.getPlanId(), trainPlanExam.getTitle());

        List<TrainPlanPaperQuestion> paperQuestions = new ArrayList<>(10);

        planExams.forEach(item -> {
            item.setPlanId(trainPlanExam.getPlanId());
            item.setCreateTime(nowDate);
        });

        int i = trainPlanExamMapper.insertTrainPlanExamBatch(new HashMap<String, Object>(1) {{
            put("planExams", planExams);
        }});

        //新增试卷记录
        trainPlanPaperMapper.insertTrainPlanPaper(paper);


        List<String> errorList = new ArrayList<>(10);

        //抽题
        planExams.forEach(item -> {
            ExamQuestion examQuestion = new ExamQuestion();
            examQuestion.setCurriculumId(item.getCurriculumId());
            examQuestion.setChapterId(item.getChapterId());
            examQuestion.setTopicType(item.getTopicType());
            List<ExamQuestion> examQuestions = examQuestionMapper.selectExamQuestionList(examQuestion);
            //该课程该章节下的该题型题目数量不够
            if (examQuestions.size() < Integer.parseInt(item.getTopicCount())) {
                Curriculum curriculum = curriculumMapper.selectCurriculumById(item.getCurriculumId());
                CurriculumChapter curriculumChapter = curriculumChapterMapper.selectCurriculumChapterById(item.getChapterId());
                errorList.add(curriculum.getName() + "课程下，章节：" + curriculumChapter.getName() + "的["
                        + CurriculumConstants.TopicTypeEnum.getTypeNameByValue(item.getTopicType().toString())
                        + "]不够，需要：" + item.getTopicCount() + "道，实际有：" + examQuestions.size() + "道");
            } else {
                examQuestions.forEach(question -> {
                    TrainPlanPaperQuestion paperQuestion = new TrainPlanPaperQuestion();
                    paperQuestion.setPaperId(paper.getId());
                    paperQuestion.setQuestionId(question.getId());
                    paperQuestion.setProblem(question.getProblem());
                    paperQuestion.setAnswer(question.getAnswer());
                    paperQuestion.setTopicType(question.getTopicType());
                    paperQuestion.setOptionJson(JSON.toJSONString(examQuestionOptionMapper.selectExamQuestionOptionList(new ExamQuestionOption() {{
                        setQuestionId(question.getId());
                    }})));
                    paperQuestion.setScore(item.getScore());
                    paperQuestions.add(paperQuestion);
                });
            }
        });

        if (!errorList.isEmpty()) {
            throw new ServiceException(JSON.toJSONString(errorList));
        }

        //新增试卷题目关联记录
        trainPlanPaperQuestionMapper.insertTrainPlanPaperQuestionBatch(new HashMap<String, Object>(1) {{
            put("paperQuestions", paperQuestions);
        }});


        return i;
    }

    /**
     * 修改培训计划抽卷
     *
     * @param trainPlanExam 培训计划抽卷
     * @return 结果
     */
    @Override
    public int updateTrainPlanExam(TrainPlanExam trainPlanExam) {
        trainPlanExam.setUpdateTime(DateUtils.getNowDate());
        return trainPlanExamMapper.updateTrainPlanExam(trainPlanExam);
    }

    /**
     * 批量删除培训计划抽卷
     *
     * @param ids 需要删除的培训计划抽卷主键
     * @return 结果
     */
    @Override
    public int deleteTrainPlanExamByIds(Long[] ids) {
        return trainPlanExamMapper.deleteTrainPlanExamByIds(ids);
    }

    /**
     * 删除培训计划抽卷信息
     *
     * @param id 培训计划抽卷主键
     * @return 结果
     */
    @Override
    public int deleteTrainPlanExamById(Long id) {
        return trainPlanExamMapper.deleteTrainPlanExamById(id);
    }
}
